﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;

namespace CommonTest.Helper
{
    public class ModelValidationError
    {
        public string FieldName { get; set; }
        public string Message { get; set; }
    }
    public class DataAnnotationHelper2
    {
        public static void test()
        {
            var a = 1;

            var b = 2;

        }

        public static IEnumerable<ModelValidationError> IsValid<T>( T o)
        {
            var descriptor = GetTypeDescriptor(typeof(T));

            foreach (PropertyDescriptor propertyDescriptor in descriptor.GetProperties())
            {
                var validations = propertyDescriptor.Attributes.OfType<ValidationAttribute>();
                foreach (var validationAttribute in validations)
                {
                    var v = propertyDescriptor.GetValue(o);

                    if (!validationAttribute.IsValid(v))
                    {
                        yield return new ModelValidationError() { FieldName = propertyDescriptor.Name, Message = validationAttribute.FormatErrorMessage(propertyDescriptor.Name) };
                    }
                }
            }
        }
        private static ICustomTypeDescriptor GetTypeDescriptor(Type type)
        {
            return null;// new AssociatedMetadataTypeTypeDescriptionProvider(type).GetTypeDescriptor(type);
        }
    }
}
